package com.xywh.micro_warehousing.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xywh.micro_warehousing.R;
import com.xywh.micro_warehousing.di.component.DaggerTab1Component;
import com.xywh.micro_warehousing.di.module.Tab1Module;
import com.xywh.micro_warehousing.mvp.contract.Tab1Contract;
import com.xywh.micro_warehousing.mvp.presenter.Tab1Presenter;
import com.xywh.micro_warehousing.mvp.ui.adapter.Tab1Adapter;
import com.xywh.micro_warehousing.mvp.ui.entity.ShenQingYuLiu;
import com.xywh.micro_warehousing.mvp.ui.entity.Tab1;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import okhttp3.RequestBody;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab1Fragment extends BaseFragment<Tab1Presenter> implements Tab1Contract.View, OnRefreshListener, OnLoadMoreListener {


    private static boolean mIsNeedDemo = true;
    protected int mStart = 1;
    protected int mNum = 10;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    TextView mBtnRight;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    Unbinder unbinder;
    private Tab1Adapter mAdapter;
    private List<Tab1.DataBean> mDataBeanList = new ArrayList<>();
    private String mSearchKeyword = "";
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    public static Tab1Fragment newInstance() {
        Tab1Fragment fragment = new Tab1Fragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab1Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab1Module(new Tab1Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab1, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
//        ToolbarUtils.initToolbarTitleNoBack(view, this, "首页");
//        mBtnRight = view.findViewById(R.id.btnRight);
//        mBtnRight.setText("添加新地址");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.autoRefresh();
    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 10, getResources().getColor(R.color.public_client_line_color)));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new Tab1Adapter(getActivity(), mDataBeanList, mSharedPreferencesHelper));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Subscriber(tag = "updateDingWeiDiZhi1", mode = ThreadMode.MAIN)
    public void updateDingWeiDiZhi1(String address) {
        if (!TextUtils.isEmpty(address))
            tvLocation.setText("当前地址：" + address);
    }

    @Subscriber(tag = "shenQingYuLiu", mode = ThreadMode.MAIN)
    public void shenQingYuLiu(Tab1.DataBean.CountersBean.MaterialsBean materialsBean) {
        try {
            showEditTextDialog(materialsBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showEditTextDialog(Tab1.DataBean.CountersBean.MaterialsBean materialsBean) {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        builder.setTitle("填写申请预留数量")
                .setPlaceholder("在此输入预留数量")
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .setDefaultText("1")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {

                            if (Double.parseDouble(text.toString()) <= Double.parseDouble(materialsBean.getStoreNum())) {

                                String jsonData = "{\n" +
                                        " \"CounterId\": " + materialsBean.getCounterId() + ",\n" +
                                        "        \"UserId\": " + mSharedPreferencesHelper.getString(BaseConstants.UID) + ",\n" +
                                        "        \"RsvNum\": " + String.valueOf(text) + ",\n" +
                                        "        \"NumUnit\": " + materialsBean.getUnit() + ",\n" +
                                        "        \"MaterialId\": \"" + materialsBean.getMId() + "\"\n" +
                                        "}";
                                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);
                                mPresenter.shenQingYuLiu(body);


                                dialog.dismiss();
                            } else {
                                showMessage("申请数量不能大于物料数量" + materialsBean.getStoreNum());
                            }

                        } else {
                            showMessage("请填入预留数量");
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void getTab1DataSuccess(Tab1 entityList) {

        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {

            mStart += entityList.getData().size();
//            mDataBeanList.clear();

            mDataBeanList.addAll(entityList.getData());
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        } else {
            if (mDataBeanList.size() > 0) {

            } else {
                mEmptyLayout.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void shenQingYuLiuSuccess(ShenQingYuLiu entityData) {
        showMessage(entityData.getMessage());

        if (entityData.getCode() == 200) {
            clearData();
            getTab1Data(mSearchKeyword);
        }
    }

    private void clearData() {
        mStart = 1;
        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
    }

    private void getTab1Data(String queryKey) {
        HashMap<String, String> map = new HashMap<>();
        map.put("queryKey", queryKey);
        map.put("longitude", mSharedPreferencesHelper.getString(BaseConstants.LONGITUDE));
        map.put("latitude", mSharedPreferencesHelper.getString(BaseConstants.LATITUDE));
        map.put("startIndex", String.valueOf(mStart));
        map.put("endIndex", String.valueOf(mStart + mNum - 1));
        mPresenter.getTab1Data(map);
    }

    @Subscriber(tag = "getSearchData", mode = ThreadMode.MAIN)
    public void getSearchData(String keyword) {
        mSearchKeyword = keyword;
        clearData();
        getTab1Data(keyword);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        clearData();
        getTab1Data("");
        mRefreshLayout.finishRefresh();

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.cancelProgressDialog(getActivity());
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getTab1Data("");
        mRefreshLayout.finishLoadMore();
    }
}
